package com.kkd.kkdapp.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.LiveHomeGridAdapter;
import com.kkd.kkdapp.adapter.LiveHomeListAdapter;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.LiveHomeData;
import com.kkd.kkdapp.http.entity.LiveHomeDataLive;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpClient;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.view.ForScrollListView;
import com.kkd.kkdapp.view.KkdListHeader;
import com.kkd.kkdapp.view.ListenBottomScrollView;
import com.kkd.kkdapp.view.ListenBottomScrollView.OnScrollToBottomListener;
import com.kkd.kkdapp.view.ScrollerLayout;
import com.kkd.kkdapp.view.ScrollerLayout.OnPullListener;
import com.kkd.kkdapp.view.ScrollerLayout.ScrollStateProvider;
import com.kkd.kkdapp.view.xlistview.XListViewHeader;

public class LiveHomeActivity extends BaseActivity {

	private Context mContext = this;

	private final int CODE_SUCCESS = 1;
	private final int CODE_FAIL = 2;
	private long pageNO = 1;
	private long pageSize = 10;
	private long pageCount;
	private ScrollerLayout mScrollerLayout;
	private View top_back;
	private LinearLayout linear_noContent;
	private ImageView iv_null;
	private TextView tv_null;
	private LinearLayout linear_content;
	private View rel_notop2;
	private ListenBottomScrollView child_scroll;
	private KkdListHeader mHeaderView;
	private ForScrollListView mListView;
	private View title_history;// 精彩回放的标题栏
	private GridView mGridView;
	private RelativeLayout rel_footer;
	private TextView tv_footer;
	private View tip_more;
	private LiveHomeListAdapter mListAdapter;
	private LiveHomeGridAdapter mGridAdapter;
	private boolean isLoadMoreing = true;
	private List<LiveHomeDataLive> list_live = new ArrayList<LiveHomeDataLive>();
	private List<LiveHomeDataLive> list_history = new ArrayList<LiveHomeDataLive>();
	private boolean REFRESHFLAG = false;
	private boolean isFirst = true;
	private boolean isShowToastOnRefresh = false;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case CODE_SUCCESS:
				LiveHomeData data = (LiveHomeData) msg.obj;
				if (!(data == null || (data.getCurrentVideo() == null
						&& data.getNextVideo() == null && (data
						.getHistoryVideos() == null || data.getHistoryVideos()
						.size() == 0)))) {
					linear_content.setVisibility(View.VISIBLE);
					linear_noContent.setVisibility(View.GONE);
					/*
					 * 设置listveiw数据
					 */
					if (pageNO == 1) {
						// 正在直播的栏目
						LiveHomeDataLive currentVideo = data.getCurrentVideo();
						if (currentVideo != null) {
							currentVideo.setLiving(true);
						}
						// 即将开播的栏目
						LiveHomeDataLive nextVideo = data.getNextVideo();
						if (nextVideo != null) {
							nextVideo.setLiving(false);
						}
						list_live.clear();
						if (currentVideo != null
								&& !TextUtils.isEmpty(currentVideo.getVid())) {
							list_live.add(currentVideo);
						}
						if (nextVideo != null
								&& !TextUtils.isEmpty(nextVideo.getVid())) {
							list_live.add(nextVideo);
						}
						mListAdapter.notifyDataSetChanged();
						if (list_live == null || list_live.size() == 0) {
							rel_notop2.setVisibility(View.VISIBLE);
						} else {
							rel_notop2.setVisibility(View.GONE);
						}
					}
					/*
					 * 设置gridveiw数据
					 */
					long PageSize = data.getPageSize();
					long totalCount = data.getTotalCount();
					if (totalCount % PageSize != 0) {
						if (totalCount == 0) {
							pageCount = 0;
						} else {
							pageCount = (totalCount / PageSize) + 1;
						}
					} else {
						pageCount = (totalCount / PageSize);
					}
					if (pageNO > pageCount) {
						setNoMore(true);
					} else {
						if (pageNO == 1) {
							list_history.clear();
						}
						list_history.addAll(data.getHistoryVideos());
						mGridAdapter.notifyDataSetChanged();
						if (data.getHistoryVideos().size() < PageSize) {
							setNoMore(true);
						} else {
							setNoMore(false);
						}
					}
					isHaveGridData(list_history != null
							&& list_history.size() > 0);
				} else {
					if (!REFRESHFLAG && isLoadMoreing) {
						linear_content.setVisibility(View.GONE);
						linear_noContent.setVisibility(View.VISIBLE);
						iv_null.setImageResource(R.drawable.live_no_content);
						tv_null.setText("暂无直播内容，请稍后再来");
					} else {
						if (linear_noContent.getVisibility() == View.VISIBLE) {
							iv_null.setImageResource(R.drawable.live_no_content);
							tv_null.setText("暂无直播内容，请稍后再来");
						}
					}
					isHaveGridData(list_history != null
							&& list_history.size() > 0);
					setNoMore(true);
				}

				if (REFRESHFLAG) {
					mScrollerLayout.clearState();
				}
				if (!isLoadMoreing) {
					isLoadMoreing = true;
				}
				if (pageNO == 1) {
					showOrHideTipMore();
				}

				if (!isShowToastOnRefresh) {
					isShowToastOnRefresh = true;
				}
				break;

			case CODE_FAIL:
				if (!REFRESHFLAG && isLoadMoreing) {
					linear_content.setVisibility(View.GONE);
					linear_noContent.setVisibility(View.VISIBLE);
					if (msg.arg1 == KkdHttpClient.NO_NET) {
						iv_null.setImageResource(R.drawable.img_null_net);
						tv_null.setText("网络错误，请稍候下拉刷新重试");
					} else {
						iv_null.setImageResource(R.drawable.img_null_net);
						tv_null.setText("服务异常，请稍候下拉刷新重试");
					}
				} else {
					if (linear_noContent.getVisibility() == View.VISIBLE) {
						if (msg.arg1 == KkdHttpClient.NO_NET) {
							iv_null.setImageResource(R.drawable.img_null_net);
							tv_null.setText("网络错误，请稍候下拉刷新重试");
						} else {
							iv_null.setImageResource(R.drawable.img_null_net);
							tv_null.setText("服务异常，请稍候下拉刷新重试");
						}
					}
				}
				isHaveGridData(list_history != null && list_history.size() > 0);
				setNoMore(true);

				if (REFRESHFLAG) {
					mScrollerLayout.clearState();
				}
				if (!isLoadMoreing) {
					isLoadMoreing = true;
				}
				if (pageNO == 1) {
					showOrHideTipMore();
				}

				String desc = (String) msg.obj;
				if (isShowToastOnRefresh) {
					if (!TextUtils.isEmpty(desc)) {
						AppUtil.makeToastForCustomer(mContext, desc);
					}
				} else {
					isShowToastOnRefresh = true;
				}
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_live_home);
		initView();
		initListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (isFirst) {
			isFirst = false;
			requestLiveHomeData();
		} else {
			updateonResume();
		}
	}

	private void initView() {
		top_back = findViewById(R.id.top_back);
		mScrollerLayout = (ScrollerLayout) findViewById(R.id.scroller_layout);
		child_scroll = (ListenBottomScrollView) findViewById(R.id.child_scroll);
		tip_more = findViewById(R.id.tip_more);
		/*
		 * 设置下拉刷新
		 */
		initRefresh();

		linear_noContent = (LinearLayout) findViewById(R.id.linear_noContent);
		iv_null = (ImageView) findViewById(R.id.iv_null);
		tv_null = (TextView) findViewById(R.id.tv_null);
		linear_content = (LinearLayout) findViewById(R.id.linear_content);
		rel_notop2 = findViewById(R.id.rel_notop2);
		title_history = findViewById(R.id.title_history);
		rel_footer = (RelativeLayout) findViewById(R.id.rel_footer);
		tv_footer = (TextView) findViewById(R.id.tv_footer);
		mListView = (ForScrollListView) findViewById(R.id.mListView);
		mListView.setFocusable(false);
		mListView.setDividerHeight(0);
		mListAdapter = new LiveHomeListAdapter(mContext, list_live);
		mListView.setAdapter(mListAdapter);
		mGridView = (GridView) findViewById(R.id.mGridView);
		mGridView.setFocusable(false);
		mGridAdapter = new LiveHomeGridAdapter(mContext, list_history);
		mGridView.setAdapter(mGridAdapter);
	}

	private void initListener() {
		// 返回键
		top_back.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				finish();
			}
		});
		// ScrollView滑倒底部监听
		child_scroll
				.setOnScrollToBottomListener(new OnScrollToBottomListener() {

					@Override
					public void onScrollToBottom() {
						if (linear_content.getVisibility() == View.VISIBLE
								&& isLoadMoreing) {
							isLoadMoreing = false;
							pageNO++;
							REFRESHFLAG = false;
							requestLiveHomeData();
						}
					}

					@Override
					public void onScroll(int scrollY) {
						if (tip_more.getVisibility() != View.GONE) {
							tip_more.setVisibility(View.GONE);
						}
					}
				});
	}

	/**
	 * 初始化刷新
	 */
	private void initRefresh() {
		mHeaderView = new KkdListHeader(mContext);
		mScrollerLayout.addTopView(mHeaderView);
		mScrollerLayout.setScrollStateProvider(new ScrollStateProvider() {

			@Override
			public boolean canPullUp() {
				return false;
			}

			@Override
			public boolean canPullDown() {

				int scrollY = child_scroll.getScrollY();
				if (scrollY == 0) {
					return true;
				}
				return false;
			}
		});
		mScrollerLayout.setOnPullListener(new OnPullListener() {

			@Override
			public void onPullUp(float pull) {

			}

			@Override
			public void onPullStateChange(byte state) {
				switch (state) {
				case ScrollerLayout.STATUS_IDLE:// 空闲状态
					mHeaderView.setVisibility(View.GONE);
					break;
				case ScrollerLayout.STATUS_PULL_DOWN:// 下拉：不满足hold条件
					mHeaderView.setVisibility(View.VISIBLE);
					mHeaderView.setState(XListViewHeader.STATE_NORMAL);
					break;
				case ScrollerLayout.STATUS_PULL_UP:// 上拉：不满足hold条件
					break;
				case ScrollerLayout.STATUS_UP_HOLD:// 上拉后等待状态
					break;
				case ScrollerLayout.STATUS_DOWN_HOLD:// 下拉后等待状态
					mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
					pageNO = 1;
					REFRESHFLAG = true;
					requestLiveHomeData();
					break;
				case ScrollerLayout.STATUS_ANIMATING:// 回弹动画状态
					break;
				case ScrollerLayout.STATUS_PULL_DOWN_ENABLE:// 下拉：满足hold条件，松开将hold
					mHeaderView.setState(XListViewHeader.STATE_READY);
					break;
				case ScrollerLayout.STATUS_PULL_UP_ENABLE: // 上拉：满足hold条件，松开将hold
					break;
				default:
					break;
				}
			}

			@Override
			public void onPullDown(float pull) {

			}
		});
	}

	/**
	 * gridview加载完了
	 * 
	 * @param noMore
	 */
	private void setNoMore(boolean noMore) {
		if (child_scroll != null) {
			child_scroll.setNoMore(noMore);
			if (noMore) {
				tv_footer.setText("没有更多内容了");
			} else {
				tv_footer.setText("正在努力刷新中，请稍后...");
			}
		}
	}

	/**
	 * 是否显示gridview上下的view
	 * 
	 * @param haveGridData
	 */
	private void isHaveGridData(boolean haveGridData) {
		if (haveGridData) {
			title_history.setVisibility(View.VISIBLE);
			rel_footer.setVisibility(View.VISIBLE);
		} else {
			title_history.setVisibility(View.GONE);
			rel_footer.setVisibility(View.GONE);
			setNoMore(true);
		}
	}

	/**
	 * 请求直播首页数据
	 */
	private void requestLiveHomeData() {
		KkdHttpMagager.getInstance().liveHomeData(pageNO, pageSize,
				LiveHomeData.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						Message msg = Message.obtain();
						msg.what = CODE_SUCCESS;
						msg.obj = responseBody;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = Message.obtain();
						msg.what = CODE_FAIL;
						msg.obj = desc;
						msg.arg1 = statusCode;
						mHandler.sendMessage(msg);
					}
				});
	}

	private long preLoadTotalCount = 0;

	/**
	 * 重新打开页面时刷新
	 */
	private void updateonResume() {
		preLoadTotalCount = list_history.size();
		long shouldLoadSize = 0;
		if (preLoadTotalCount <= 0) {
			shouldLoadSize = 1;
		} else if (preLoadTotalCount > 0 && preLoadTotalCount <= 10) {
			shouldLoadSize = 10;
		} else {
			shouldLoadSize = preLoadTotalCount;
		}
		KkdHttpMagager.getInstance().liveHomeData(1, shouldLoadSize,
				LiveHomeData.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						LiveHomeData curData = (LiveHomeData) responseBody;
						if (!(curData == null || (curData.getCurrentVideo() == null
								&& curData.getNextVideo() == null && (curData
								.getHistoryVideos() == null || curData
								.getHistoryVideos().size() == 0)))) {
							/*
							 * 设置listveiw数据
							 */
							// 正在直播的栏目
							LiveHomeDataLive curCurrentVideo = curData
									.getCurrentVideo();
							if (curCurrentVideo != null) {
								curCurrentVideo.setLiving(true);
							}
							// 即将开播的栏目
							LiveHomeDataLive curNextVideo = curData
									.getNextVideo();
							if (curNextVideo != null) {
								curNextVideo.setLiving(false);
							}
							list_live.clear();
							if (curCurrentVideo != null
									&& !TextUtils.isEmpty(curCurrentVideo
											.getVid())) {
								list_live.add(curCurrentVideo);
							}
							if (curNextVideo != null
									&& !TextUtils.isEmpty(curNextVideo.getVid())) {
								list_live.add(curNextVideo);
							}
							mListAdapter.notifyDataSetChanged();
							if (list_live == null || list_live.size() == 0) {
								rel_notop2.setVisibility(View.VISIBLE);
							} else {
								rel_notop2.setVisibility(View.GONE);
							}

							if (tip_more.getVisibility() != View.GONE) {
								showOrHideTipMore();
							}

							/*
							 * 设置gridveiw数据
							 */
							try {
								if (preLoadTotalCount > 0) {
									int curLoadTotalCount = curData
											.getHistoryVideos().size();
									if (preLoadTotalCount > 10) {
										if (curLoadTotalCount == preLoadTotalCount) {
											list_history.clear();
											list_history.addAll(curData
													.getHistoryVideos());
											mGridAdapter.notifyDataSetChanged();
										}
									} else {
										if (curLoadTotalCount > 0) {
											list_history.clear();
											list_history.addAll(curData
													.getHistoryVideos());
											mGridAdapter.notifyDataSetChanged();
										}
									}

								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {

					}
				});
	}

	private void showOrHideTipMore() {
		if (list_history == null || list_history.size() == 0) {
			tip_more.setVisibility(View.GONE);
		} else {
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					if (list_history == null || list_history.size() == 0) {
						tip_more.setVisibility(View.GONE);
					} else {
						View view = (View) child_scroll.getChildAt(child_scroll
								.getChildCount() - 1);
						if (view.getBottom() <= child_scroll.getHeight()) {
							tip_more.setVisibility(View.GONE);
						} else {
							tip_more.setVisibility(View.VISIBLE);
						}
					}
				}
			}, 100);
		}
	}

	/**********
	 * 视频分享成功
	 **********/
	@Override
	public void videoShareSuccess() {
		String vid = list_live.get(0).getVid();
		LogUtil.e("TAG", "视频分享成功了vid------>" + vid);
		KkdHttpMagager.getInstance().getLiveShare(vid, String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						LogUtil.e("TAG", "视频分享上传成功了");
					}

					@Override
					public void onFailure(int statusCode, String desc) {

					}
				});
	}
}
